//
//  BKOperation.m
//  XPhoto
//
//  Created by baboy on 2019/6/25.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "BKOperation.h"

@implementation BKOperation
- (id)init{
    if (self = [super init]) {
        _executionBlocks = [NSMutableArray array];
        _finished = NO;
        _executing = NO;
        _asynchronous = NO;
    }
    return self;
}
+ (instancetype)blockOperationWithBlock:(void (^)(void))block{
    id operation = [[self alloc] init];
    [operation addExecutionBlock:block];
    return operation;
}

- (void)addExecutionBlock:(void (^)(void))block{
    [(NSMutableArray*)self.executionBlocks addObject:block];
}
- (BOOL)isAsynchronous{
    return _asynchronous;
}
- (void)setAsynchronous:(BOOL)asynchronous{
    _asynchronous = asynchronous;
}
- (BOOL)isFinished{
    return _finished;
}
- (BOOL)isExecuting{
    return _executing;
}
- (void)updateFinishedStatus:(BOOL)flag{
    if (_finished == flag) {
        return;
    }
    [self willChangeValueForKey:@"isFinished"];
    _finished = flag;
    [self didChangeValueForKey:@"isFinished"];
    
    if (flag) {
        [self updateExecutingStatus:NO];
    }
}

- (void)updateExecutingStatus:(BOOL)flag{
    if (_executing == flag) {
        return;
    }
    [self willChangeValueForKey:@"isExecuting"];
    _executing = flag;
    [self didChangeValueForKey:@"isExecuting"];
}
- (void)exe{
    for (NSInteger i = 0; i<self.executionBlocks.count; i++) {
        void(^b)(void) = [self.executionBlocks objectAtIndex:0];
        b();
    }
    if (!self.isAsynchronous) {
        [self updateFinishedStatus:YES];
        return;
    }
    [self updateExecutingStatus:YES];
}
- (void)start{
    if ([self isCancelled]) {
        [self updateFinishedStatus:YES];
        return;
    }
    [self updateExecutingStatus:YES];
    [self exe];
}

//- (void)main{
//    //execute block
//}
@end
